# -*- coding: utf-8 -*-
from article import Article
import csv

from db import get_db


class ArticleStorage:
    def save(self, article: Article):
        pass


class ArticleCSVStorage:
    def __init__(self, filename):
        self.filename = filename

    def save(self, article: Article):
        with open(self.filename, 'a', encoding='utf-8', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(
                [article.article_id, article.provide_code, article.article_date, article.article_time, article.headline,
                 article.article_text])
            f.close()


class ArticleMYSQLStorage:
    def save(self, article: Article):
        db = get_db()
        cursor = db.cursor()
        sql = "INSERT INTO article (article_id, symbol, article_date, article_time, provider_code, headline, article_text) VALUES (%s,%s, %s, %s, %s, %s, %s)"
        values= (article.article_id, article.symbol, article.article_date, article.article_time,
                     article.provide_code, article.headline, article.article_text)
        print(sql)
        cursor.execute(sql, values)
        db.commit()
        db.close()

    def getArticle(self, article_id: str):
        db = get_db()
        cursor = db.cursor()
        sql = "SELECT article_id, symbol, article_date, article_time, provider_code, headline, article_text FROM article WHERE article_id = %s"
        values = (article_id)
        print(sql)
        cursor.execute(sql, values)
        result = cursor.fetchone()
        db.commit()
        db.close()
        if result is not None:
            return Article(article_id=result[0], symbol=result[1], article_date=result[2], article_time=result[3], provider_code=result[4], headline=result[5], article_text=result[6])
        return None
